<template>
  <div class="price-comparison">
    <!-- 价格比对图表 -->
    <div class="chart-container" style="width: 100%; height: 300px">
      <!-- <div>{{ priceDataList }}</div> -->
      <div ref="priceChart" class="price-chart"></div>
    </div>

    <!-- 价格分析表格 -->
    <div class="price-analysis">
      <div class="title">价格分析</div>
      <el-table :data="priceDataList" border stripe>
        <el-table-column prop="source" label="来源" width="120" />
        <el-table-column prop="unitPrice" label="租赁单价(元/m²/月)">
          <template #default="{ row }">
            {{ row.unitPrice ? `${row.unitPrice}` : "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="deviationAmplitude" label="偏差幅度">
          <template #default="{ row }">
            <span v-if="row.deviationAmplitude !== null">
              <span
                :style="
                  Math.abs(Number(row.deviationAmplitude)) > 20
                    ? { color: '#ef4444', fontWeight: 'bold' }
                    : { color: '#10b981' }
                "
              >
                {{ row.deviationAmplitude > 0 ? "+" : ""
                }}{{ row.deviationAmplitude }}%
              </span>
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="time" label="采集时间" width="180" />
      </el-table>
    </div>

    <!-- 分析结果 -->
    <div class="analysis-result">
      <!-- <el-alert
        v-if="!hasDeviationOver20"
        type="success"
        title="春熙路临时建筑租赁单价正常。"
        :closable="false"
        show-icon
      /> -->
      <el-alert
        type="error"
        title="春熙路临时建筑租赁单价偏差幅度突破±20%。"
        :closable="false"
        show-icon
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted, computed } from "vue";
import * as echarts from "echarts";

const props = defineProps({
  assetData: {
    type: Object,
    required: true,
  },
});

const sourceOrder = ["价格比对", "评估价格", "线下价格", "线上价格"];

const priceDataList = computed(() => {
  if (!props.assetData) return [];
  // 深拷贝
  let arr = JSON.parse(JSON.stringify(props.assetData));
  // 排序
  arr.sort(
    (a, b) => sourceOrder.indexOf(a.source) - sourceOrder.indexOf(b.source)
  );
  // 找到价格比对
  const rent = arr.find((item) => item.source === "价格比对");
  // 计算偏差幅度
  return arr.map((item) => {
    if (item.source === "价格比对") {
      return { ...item, deviationAmplitude: null };
    }
    if (rent && rent.unitPrice && item.unitPrice) {
      const deviation =
        ((rent.unitPrice - item.unitPrice) / rent.unitPrice) * 100;
      return { ...item, deviationAmplitude: deviation.toFixed(2) };
    }
    return { ...item, deviationAmplitude: null };
  });
});

const analysisResults = computed(() => {
  if (!props.assetData?.analysisResults) return [];
  return JSON.parse(JSON.stringify(props.assetData.analysisResults));
});

const priceChart = ref(null);
let chart = null;

// 定义颜色映射
const colorMap = {
  线上价格: "#5EEAD4",
  线下价格: "#7DD3FC",
  评估价格: "#FCD34D",
  价格比对: "#93C5FD",
};

// 取最大绝对偏差幅度
const maxDeviation = computed(() => {
  if (!props.assetData.length) return 0;
  return Math.max(
    ...props.assetData
      .map((item) => Math.abs(Number(item.deviationAmplitude)))
      .filter((v) => !isNaN(v))
  );
});

// 判断是否超出±20%
const isOver20 = computed(() => maxDeviation.value > 20);

const hasDeviationOver20 = computed(() => {
  return priceDataList.value.some(
    (row) =>
      row.deviationAmplitude !== null &&
      Math.abs(Number(row.deviationAmplitude)) > 20
  );
});

// 初始化图表
const initChart = () => {
  console.log(2222, priceChart.value, priceDataList.value);

  if (!priceChart.value || !priceDataList.value.length) return;

  const chartDom = priceChart.value;
  chart = echarts.init(chartDom);

  const option = {
    xAxis: {
      type: "category",
      data: priceDataList.value.map((item) => item.source),
      axisLine: {
        lineStyle: {
          color: "#E5E7EB",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        interval: 0,
        color: "#333",
      },
    },
    yAxis: {
      type: "value",
      name: "元/m²/月",
      nameTextStyle: {
        color: "#666",
      },
      splitLine: {
        lineStyle: {
          color: "#E5E7EB",
          type: "dashed",
        },
      },
      axisLabel: {
        color: "#666",
      },
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      left: "5%",
      right: "4%",
      bottom: "8%",
      top: "12%",
      containLabel: true,
    },
    series: [
      {
        data: priceDataList.value.map((item) => ({
          value: item.unitPrice ? Number(item.unitPrice) : null,
          itemStyle: {
            color: colorMap[item.source] || "#5EEAD4",
          },
        })),
        type: "bar",
        barWidth: "40%",
        label: {
          show: true,
          position: "top",
          formatter: (params) => (params.value ? params.value : "--"),
          color: "#666",
        },
      },
    ],
  };

  chart.setOption(option);
};

// 监听数据变化重新渲染图表
watch(
  () => priceDataList.value,
  () => {
    if (chart) {
      chart.dispose();
    }
    nextTick(() => {
      initChart();
    });
  },
  { deep: true }
);

onMounted(() => {
  nextTick(() => {
    initChart();
  });
});

// 组件卸载时清理
onUnmounted(() => {
  if (chart) {
    chart.dispose();
    chart = null;
  }
});
</script>

<style lang="scss" scoped>
.price-comparison {
  padding: 0 20px;

  .asset-info {
    margin-bottom: 24px;

    .asset-title {
      margin-bottom: 12px;

      .name {
        font-size: 16px;
        font-weight: 500;
        color: #111827;
      }

      .code {
        margin-left: 12px;
        font-size: 14px;
        color: #6b7280;
      }
    }

    .asset-meta {
      font-size: 14px;

      .label {
        color: #6b7280;
      }

      .value {
        color: #111827;
      }

      .ml20 {
        margin-left: 20px;
      }
    }
  }

  .chart-container {
    margin: 24px 0;
    background: #fff;
    height: 300px !important;
    .price-chart {
      width: 100%;
      height: 100%;
    }
  }

  .price-analysis {
    margin-bottom: 24px;

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #111827;
      margin-bottom: 16px;
    }

    .difference {
      &.up {
        color: #10b981;
      }
      &.down {
        color: #ef4444;
      }
    }
  }

  .analysis-result {
    :deep(.el-alert) {
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
</style>
